package com.fy.fyspace.task;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fy.fyspace.common.manager.AiTaskQueueManager;
import com.fy.fyspace.common.manager.CosManager;
import com.fy.fyspace.mapper.AipictureMapper;
import com.fy.fyspace.model.entity.Aipicture;
import com.fy.fyspace.model.enums.aipicture.AiPictureTaskStatusEnum;
import com.fy.fyspace.model.vo.outpainting.GetOutPaintingTaskVO;
//import com.fy.fyspace.service.AIService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * AI任务状态检查定时任务
 */
@Slf4j
@Component
@EnableScheduling
public class AiTaskStatusChecker {

    @Resource
    private AiTaskQueueManager aiTaskQueueManager;

    @Autowired
    private AipictureMapper aipictureMapper;

//    @Resource
//    private AIService aiService;

    @Resource
    private CosManager cosManager; // 添加COS管理器

    @Resource(name = "aiTaskThreadPool")
    private ThreadPoolExecutor aiTaskThreadPool;

    /**
     * 定时检查AI任务状态
     * 每10秒执行一次
     */
    @Scheduled(fixedRate = 10000)
    public void checkTaskStatus() {
        log.debug("开始检查AI任务状态");

        Set<Object> tasks = aiTaskQueueManager.getAllTasks();
        if (CollUtil.isEmpty(tasks)) {
            return;
        }

        log.info("获取到{}个待处理AI任务", tasks.size());

        tasks.forEach(taskId -> CompletableFuture.runAsync(() -> {
            try {
                LambdaQueryWrapper<Aipicture> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Aipicture::getTaskId, taskId);
                Aipicture aipicture = aipictureMapper.selectOne(wrapper);
                String status = aipicture.getTaskStatus();

                if (aipicture == null || AiPictureTaskStatusEnum.SUCCESS.getCode().equals(status)
                        || AiPictureTaskStatusEnum.FAILED.getCode().equals(status)) {
                    log.warn("未找到任务信息或任务已完成: taskId={}, status={}", taskId, status);
                    aiTaskQueueManager.removeTask((String) taskId);
                    return;
                }

//                GetOutPaintingTaskVO outpaintingTaskStatus = aiService.getOutpaintingTaskStatus((String) taskId);
                GetOutPaintingTaskVO outpaintingTaskStatus = null;
                GetOutPaintingTaskVO.Output output = outpaintingTaskStatus.getOutput();

                if (output != null) {
                    // 更新基本信息
                    if (outpaintingTaskStatus.getRequestId() != null) {
                        aipicture.setRequestId(outpaintingTaskStatus.getRequestId());
                    }
                    if (output.getCode() != null) {
                        aipicture.setCode(output.getCode());
                    }
                    if (output.getMessage() != null) {
                        aipicture.setMessage(output.getMessage());
                    }
                    if (output.getOutputImageUrl()!=null){
                        aipicture.setAiUrl(output.getOutputImageUrl());
                    }
                    if(output.getEndTime()!=null){
                        aipicture.setAiUrlOutTime(output.convertToDate());
                    }

                    // 更新任务状态
                    if (output.getTaskStatus() != null) {
                        aipicture.setTaskStatus(output.getTaskStatus());
                        log.info("更新任务状态: taskId={}, status={}", taskId, output.getTaskStatus());
                    }

                    // 如果任务成功，处理图片
                    if (AiPictureTaskStatusEnum.SUCCESS.getCode().equals(output.getTaskStatus())) {
                        if (output.getOutputImageUrl() != null) {
                            try {
                                // 1. 下载扩图结果
                                String imageUrl = output.getOutputImageUrl();
                                log.info("开始下载扩图结果: taskId={}, url={}", taskId, imageUrl);

                                // 创建临时文件
                                String fileName = "ai_" + taskId + "_" + System.currentTimeMillis() + ".png";
                                File tempDir = new File("temp");
                                if (!tempDir.exists()) {
                                    tempDir.mkdir();
                                }
                                File tempFile = new File(tempDir, fileName);

                                // 下载文件
                                URL url = new URL(imageUrl);
                                FileUtils.copyURLToFile(url, tempFile);
                                log.info("扩图结果下载完成: taskId={}, tempFile={}", taskId, tempFile.getAbsolutePath());

                                // 2. 上传到腾讯云COS
                                String cosPath = "/ai/" + fileName;
                                cosManager.putObject(cosPath, tempFile);
                                log.info("扩图结果上传到COS完成: taskId={}, cosPath={}", taskId, cosPath);

                                // 3. 更新数据库记录
                                aipicture.setTaskId(cosPath);
                                // 生成缩略图URL
                                String thumbnailUrl = cosPath + "?imageMogr2/format/webp/quality/60";
                                aipicture.setThumbnailUrl(thumbnailUrl);

                                // 4. 清理临时文件
                                if (tempFile.exists()) {
                                    tempFile.delete();
                                }
                                log.info("临时文件清理完成: taskId={}", taskId);

                            } catch (Exception e) {
                                log.error("处理扩图结果失败: taskId={}, error={}", taskId, e.getMessage());
                                aipicture.setTaskStatus(AiPictureTaskStatusEnum.FAILED.getCode());
                                aipicture.setMessage("处理扩图结果失败: " + e.getMessage());
                            }
                        }
                    }
                }

                // 更新时间
                aipicture.setUpdateTime(new Date());
                aipictureMapper.updateById(aipicture);

                // 如果任务已完成，从队列中移除
                if (AiPictureTaskStatusEnum.SUCCESS.getCode().equals(aipicture.getTaskStatus()) ||
                        AiPictureTaskStatusEnum.FAILED.getCode().equals(aipicture.getTaskStatus())) {
                    aiTaskQueueManager.removeTask((String) taskId);
                    log.info("AI任务已完成，从队列中移除: taskId={}, status={}", taskId, aipicture.getTaskStatus());
                }

            } catch (Exception e) {
                log.error("处理AI任务状态更新失败: taskId={}, error={}", taskId, e.getMessage());
            }
        }, aiTaskThreadPool));
    }
}